package demo.ClassLoad;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/8/5-08-05-11:18
 * @Description：demo.ClassLoad    反射获取信息并使用
 */
public class reflect_use {
    public static void main(String[] args) throws Exception {
        //反射赋值
        Class<Student> c = Student.class;
        Student stu = new Student();
        Object o = c.newInstance();
        System.out.println(o);

        //public 字段
        Field field = c.getDeclaredField("name");
        field.set(stu,"hjy");   //Student.name = "hjy"     //field.set(null,"hjy")   公有的字段可以不通过对象赋值
        System.out.println(field.get(stu));    // == stu.name

        //私有字段
        Field sno = c.getDeclaredField("sno");
        sno.setAccessible(true);    //暴力访问私有变量
        sno.set(stu,1);
        System.out.println(sno.get(stu));

        //final修饰的基本数据类型字段
        Field age = c.getDeclaredField("age");

        if(Modifier.toString(age.getModifiers()).contains("final")){
            System.out.println("final修饰，谨慎更改！");
        }else{
            age.setAccessible(true);    //暴力访问常量 强制更改        无法更改static + final 修饰的变量
            age.set(stu,12);
            System.out.println(age.get(stu));
        }

        //final修饰的引用字段
//        Field per = c.getDeclaredField("student");
//        per.setAccessible(true);    //暴力访问常量 强制更改
//        per.set(stu,(Student)o);
//        System.out.println(per.get(stu));

        //多参构造器调用创建实例
        Constructor<Student> constructor = c.getDeclaredConstructor(String.class, int.class);
        //Object hjy = constructor.newInstance("hjy",12);
        Object hjy = constructor.newInstance("hjy",12);
        System.out.println(hjy);

        //私有构造器调用创建实例     反射可以破坏单例模式 ，可以调用私有构造器
        Constructor<Student> constructor2 = c.getDeclaredConstructor(String.class);
        Object hjy2 = constructor2.newInstance("hhh");
        System.out.println(hjy2);
    }
}
